package na.learn.java.jmx.sampleprogs.stdmbean;

import javax.management.InstanceAlreadyExistsException;
import javax.management.MBeanRegistrationException;
import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
import javax.management.MalformedObjectNameException;
import javax.management.NotCompliantMBeanException;
import javax.management.Notification;
import javax.management.NotificationListener;
import javax.management.ObjectName;

import com.sun.jdmk.comm.HtmlAdaptorServer;

public class CacheManagerAgent implements NotificationListener {

	private MBeanServer beanServer;

	public CacheManagerAgent() {
		super();

		beanServer = MBeanServerFactory.createMBeanServer(""
				+ SimpleCache.class);
		HtmlAdaptorServer htmlAdapter = new HtmlAdaptorServer();
		SimpleCache cache = new SimpleCache();
		ObjectName cacheObjectName = null;
		ObjectName adapterObjectName = null;

		try {
			
			adapterObjectName = new ObjectName("CacheManagerAgent:name=htmlAdapter1, port=9093");
			beanServer.registerMBean(htmlAdapter, adapterObjectName);
			htmlAdapter.setPort(9093);			
			htmlAdapter.start();
			
			
			cacheObjectName = new ObjectName("CacheManagerAgent:name=SimpleCache1");
			beanServer.registerMBean(cache, cacheObjectName);
			cache.addNotificationListener(this, null, null);

		} catch (MalformedObjectNameException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NullPointerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InstanceAlreadyExistsException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MBeanRegistrationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NotCompliantMBeanException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public void handleNotification(Notification notif, Object handback) {
		if(notif.getClass().getCanonicalName().indexOf("AttributeChangeNotification") != -1){
		System.out.println("Got notification from " + notif.getSource());
		System.out.println("Got Message: " + notif.getMessage());
		}

	}
	
	
	public static void main(String[] args) {
		CacheManagerAgent agent = new CacheManagerAgent();
	}

}
